package com.mar.bt.server.impl;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;

import net.java.dev.marge.entity.Device;
/**
 * BTOutput stream for generic bt device 
 * @author mar
 *
 */
class BTOutputStream extends OutputStream {
	protected final Device btDevice;
	
	BTOutputStream(Device clientDEvice){
		this.btDevice = clientDEvice;
	}
	
	protected final ByteBuffer buffer = ByteBuffer.wrap(new byte [ 1024*100 ] );// 100kb
	
	public void write(int b) throws IOException {
		buffer.put((byte) b );
	}
	
	public void flush() throws IOException {
		buffer.flip();
		
		// extract data
		flushDataToBTDevice();
		
		buffer.clear();		
	}

	protected void flushDataToBTDevice() {
		byte[] dataToSend = new byte[buffer.limit()];
		buffer.get( dataToSend);
		btDevice.send(dataToSend);
	}
	
	public void close(){
		btDevice.close();
	}
}
